package com.xh.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 * @author admin
 *
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session=request.getSession();
		String userToken=(String) session.getAttribute("userToken");
		if(StringUtils.isEmpty(userToken)){
			//userToken为空
			logger.error("userToken为空,没有获取到用户信息");
			response.sendError(500);
			return false;
		}else{
			try {
				//更新session失效时间，30分钟
				session.setMaxInactiveInterval(30*60);

			} catch (Exception e) {
				logger.error("刷新用户token在redis中的有效时间失败");
				return false;
			}
		}
			return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
